<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
		<meta name="apple-mobile-web-app-capable" content="yes" />

		<title>SVERIGES HJÄRTSTARTARREGISTER</title>

		<link rel="apple-touch-icon" href="styles/touch-icon.png?v=1" />
		<link rel="stylesheet" type="text/css" href="styles/style.css?v=1">
		<link rel="stylesheet" type="text/css" href="styles/font-awesome.min.css?v=1">

	    <!-- API key for "Hjärtstartarregistret", https://code.google.com/apis/console/?pli=1#project:165583540177:overview with google account hjartstartarregistret@gmail.com -->
	    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyBr1zj9GA_zO0uYWyvQz48T9EbTIE4Gvxo&sensor=true&language=sv&region=SV"></script>
	    <!-- http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.9/docs/reference.html -->
    	<script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.9/src/markerclusterer_packed.js"></script>
	    <!-- http://google-maps-utility-library-v3.googlecode.com/svn/trunk/geolocationmarker/docs/reference.html -->
    	<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/geolocationmarker/src/geolocationmarker-compiled.js"></script>

    <script type="text/javascript">(function() {
      'use strict';

      window.HR = {};
      HR.buildKmlRequestUrl = function(bboxParam) {
		//var authKey = '6962b285-c2e3-4f08-a2c1-0cece7d7d432';
		var authKey = '7702b285-c2e3-4f08-a2c1-0cece7d7d645';
		var requestUrl= 'http://geo.hjartstartarregistret.se/geoserver/wms?authkey=' + authKey + '&LAYERS=HjaertstartarPositionsVy&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&FORMAT=kml&SRS=EPSG%3A4236&BBOX=' + bboxParam + '&WIDTH=10&HEIGHT=10';
		// If we are to make direct HTTP request to the geoserver, we need either to be on same domain or make them enable the "Access-Control-Allow-Origin" header. Bypass that for now with:
		if (location.href.indexOf('hjartstartarregistret.se') == -1) requestUrl = '/?url=' + encodeURIComponent(requestUrl);
		return requestUrl;
      }
      HR.domParser = new DOMParser();
      HR.visibleMarkersMap = {}; // Mapping from id to marker
      HR.activeInfoWindow = null;
      HR.currentPositionMarker = null;
      HR.centerOfSweden = new google.maps.LatLng(62.3875, 16.3255);
      HR.initialZoom = 16;
      HR.searchMarkers = [];

      google.maps.event.addDomListener(window, 'load', function() {
	google.maps.visualRefresh = true; // https://developers.google.com/maps/documentation/javascript/basics#VisualRefresh
        var map = new google.maps.Map(document.getElementById("map-canvas-page"), {
		  center: HR.centerOfSweden,
		  zoom: 5,
		  minZoom: 5,
		  panControl: true,
		  panControlOptions: {
		  	position: google.maps.ControlPosition.LEFT_BOTTOM
	          },
		  zoomControl: true,
		  zoomControlOptions: {
			style: google.maps.ZoomControlStyle.LARGE,
			position: google.maps.ControlPosition.LEFT_BOTTOM
		  },
		  mapTypeId: google.maps.MapTypeId.ROADMAP,
		  mapTypeControlOptions: { mapTypeIds: [] } // Remove controls for switching maptypes (satelleite, etc)
	});
	HR.map = map;
	HR.markerCluster = new MarkerClusterer(map, []);

	var geoMarker = new GeolocationMarker();
	geoMarker.setCircleOptions({fillColor: '#808080'});
	google.maps.event.addListenerOnce(geoMarker, 'position_changed', function() {
	  	map.setCenter(this.getPosition());
		map.setZoom(HR.initialZoom);
	});
	google.maps.event.addListenerOnce(geoMarker, 'geolocation_error', function(positionError) { console.log(JSON.stringify(positionError)); });
	geoMarker.setMap(map);

	HR.clearOverlaysOutsideMap = function() {
	      	var bounds = map.getBounds();
	      	var toRemove = [];
		for (var placeId in HR.visibleMarkersMap) {
			var marker = HR.visibleMarkersMap[placeId];
			if (!bounds.contains(marker.getPosition())) {
				// Not visible, remove from cluster, map and our visibleMarkersMap:
				// console.log('removing invisible: ' + placeId);
				if (marker.__ppAddedToCluster) { HR.markerCluster.removeMarker(marker); marker.__ppAddedToCluster = false; }
				marker.setMap(null);
				toRemove.push(marker);
			}
		}
		for (var i = 0; i < toRemove.length; i++) delete HR.visibleMarkersMap[toRemove[i].__ppId];
		// console.log('after clearOverlaysOutsideMap, still visible=' + Object.keys(HR.visibleMarkersMap).length);
	}

	HR.setSpinning = function(spinning) {
		toggleClassName(document.getElementById("logo"), "icon-spinner icon-spin");
	}

	var searchBox = new google.maps.places.SearchBox(document.getElementById('search'), {
		bounds: new google.maps.LatLngBounds(new google.maps.LatLng(-9.174757593749973,55.744950883650475), new google.maps.LatLng(51.16215646875003,68.87494061751826)) // Sweden
	});

	google.maps.event.addListener(searchBox, 'places_changed', function() {
  	  for (var i = 0; i < HR.searchMarkers.length; i++) HR.searchMarkers[i].setMap(null);
  	  HR.searchMarkers = [];

	  var places = searchBox.getPlaces();
	  var bounds = new google.maps.LatLngBounds();
	  for (var i = 0, place; place = places[i]; i++) {
	    bounds.extend(place.geometry.location);
	    var marker = new google.maps.Marker({map: map, title: place.name, position: place.geometry.location });
	    HR.searchMarkers.push(marker);
	  }
	  map.fitBounds(bounds);
	  if (places.length == 1) map.setZoom(HR.initialZoom);
	});
	
	google.maps.event.addListener(map, 'bounds_changed', function() {
	    var bounds = map.getBounds();
	    searchBox.setBounds(bounds);
	 });

	google.maps.event.addListener(map, 'idle', function() {
		// The 'idle' event is triggered whenever the map is finished redrawing after a scroll or zoom change
		var bounds = map.getBounds(), ne = bounds.getNorthEast(), sw = bounds.getSouthWest();
		var bboxParam = sw.lng() + ',' + sw.lat() + ',' + ne.lng() + ',' + ne.lat();  // minx,miny,maxx,maxy
		var requestUrl = HR.buildKmlRequestUrl(bboxParam);
		var origRequest = requestUrl;
		if (HR.latestGeoRequest) HR.latestGeoRequest.abort();
		var xhr = new XMLHttpRequest();
		HR.setSpinning(true);
		xhr.onreadystatechange = function() {
			if (xhr.readyState != 4) return;
			HR.setSpinning(false);
			HR.latestGeoRequest = null;

			if (!xhr.responseXML) {
				//console.log('No responseXML for request: ' + origRequest + ', responseText=' + xhr.responseText);
				return;
			}
			var places = xhr.responseXML.getElementsByTagName('Placemark');
			// console.log('got ' + places.length + ' places for origUrl=' + origRequest);
			for (var i = 0; i < places.length; i++) {
				var place = places.item(i); // NOTE: The "id" attribute of a Placemark is not persistent
				var lat = place.getElementsByTagName('latitude')[0].textContent;
				var lng = place.getElementsByTagName('longitude')[0].textContent;
				var attributesMap = getAttributesMap(place);
				var placeId = lat + ',' + lng;
				if (HR.visibleMarkersMap[placeId]) continue; // Skip already visible place.
				var latLng = new google.maps.LatLng(lat, lng);
				var description = '<h4>' + attributesMap['Innehavare'] + '</h4><ul class="description-list">';
				var icon;
				if (attributesMap['NuvarandeTillstaand'] == 'Kontrollerad') {
					var tiderDescription = '<ul>';
					var openNow = false;
					var tiderContainer = attributesMap['TillgaengligaTider'];
					if (tiderContainer) {
						var tiderElements = tiderContainer.getElementsByTagName('tillgaengligTid');
						for (var j = 0; j < tiderElements.length; j++) {
							var tid = tiderElements.item(j);
							var tidsPeriod = tid.getElementsByTagName('tidsperiod')[0].textContent;
							var dagar = tid.getElementsByTagName('dagar')[0].textContent;
							var tider = tid.getElementsByTagName('tider')[0].textContent;
							if (isOpenNow(tidsPeriod, dagar, tider)) openNow = true;
							tiderDescription += '<li><span id="attre-value-period">' + tidsPeriod + '</span>, <span id="attre-value-days">' + dagar + '</span> <span id="attre-value-time">' + tider + '</span></li>';	
						}
					}
					tiderDescription += '<li><span class="'+ (openNow ? 'available' : 'not-available') +'">' + (openNow ? 'Tillgänglig' : 'Ej Tillgänglig') + '</span></li>';
					tiderDescription += '</ul>';	
					description += '<li><span class="attr-name" id="attr-name-adress">Adress:</span> <span class="attr-value" id="attre-value-adress">' + attributesMap['Adress'] + '</span></li><li><span class="attr-name" id="attr-name-location">Placering:</span> <span class="attr-value" id="attre-value-vaaningsplan">Våningsplan ' + attributesMap['Vaaningsplan'] + '</span>, <span class="attr-value" id="attre-value-placement">'+ attributesMap['Placering'] +'</span></li><li><span class="attr-name" id="attr-name-hours">Öppettider:</span> <span class="attr-value" id="attr-value-hours">' + tiderDescription + '</span></li>';
					if (openNow) {
						icon = 'styles/hjartstartGreen.png';
					} else {
						icon = 'styles/hjartstartGrey.png';
					}
					description += '</ul>';

					var marker = new google.maps.Marker({ position: latLng, map: map, icon:icon });
					HR.visibleMarkersMap[placeId] = marker;
					marker.__ppId = placeId;
					marker.__ppAddedToCluster = false;
					marker.__ppAttributesMap = attributesMap;
					//marker.__ppOpenNow = openNow;
					marker.__ppIconPath = icon;
	
					(function(localMarker, localPlace, localDescription) {
						google.maps.event.addListener(localMarker, 'click', function() {
							if (HR.activeInfoWindow) HR.activeInfoWindow.close();
							HR.activeInfoWindow = new google.maps.InfoWindow({
								content: localDescription,
								size: new google.maps.Size(250,250)
							});
							HR.activeInfoWindow.open(map, localMarker);
						})
					})(marker, place, description);
				}
			}

			HR.clearOverlaysOutsideMap();
			HR.updateLocationList();

			/*
			if (false && map.getZoom() <= 14) {
				for (var placeId in HR.visibleMarkersMap) {
					var marker = HR.visibleMarkersMap[placeId];
					if (!marker.__ppAddedToCluster) {
						marker.__ppAddedToCluster = true;
						HR.markerCluster.addMarker(marker);
					}
				}
			} else {
				// Zoomed in, no clustering:
				for (var placeId in HR.visibleMarkersMap) {
					var marker = HR.visibleMarkersMap[placeId];
					marker.__ppAddedToCluster = false;
					HR.markerCluster.removeMarker(marker);
				}
			}
			*/
		};
		xhr.open("GET", requestUrl, true);
		xhr.send();
		HR.latestGeoRequest = xhr;
	});

      });
			function getAttributesMap(place) {
				var megaDescription = place.getElementsByTagName('description')[0].textContent;
				if (megaDescription.indexOf('&') != -1) megaDescription = megaDescription.replace('&', '&amp;');
				var descriptionDoc = HR.domParser.parseFromString('<doc>' + megaDescription + '</doc>', 'text/xml');
				var attributesElements = descriptionDoc.getElementsByTagName('li');
				var attributesMap = {};
				for (var j = 0; j < attributesElements.length; j++) {
					var attr = attributesElements.item(j);
					var attributeName = attr.getElementsByTagName('span')[0].textContent;
					if (attributeName == 'TillgaengligaTider') {
						var attributeValue = attr.getElementsByTagName('span')[1];
					} else {
						var attributeValue = attr.getElementsByTagName('span')[1].textContent;
					}
					attributesMap[attributeName] = attributeValue;
				}
				return attributesMap;
				
			}
			function closeSearchAndMenu() {
				document.getElementById("nav-search").className = "";
				document.getElementById("nav-menu").className = "";
			}
			HR.showSearchOrMenu = function(id) {
				var element = document.getElementById(id);
				if (element != null) {
					if (containsClassName(element, 'active')) {
						closeSearchAndMenu();
						makeMapLocationListAvalible();
					} else {
						closeSearchAndMenu();
						addClassName(element, 'active');
						makeMapLocationListUnavilible();
					}
				}
			}
			
			function containsClassName(element, className) {
				return (element.className.indexOf(className) != -1);
			}
			function addClassName(element, className) {
				if (element.className.length > 0) {
					element.className += ' ';
				}
				element.className += className;
			}
			function removeClassName(element, className) {
				var regex = new RegExp('(?:^|\s)' + className + '(?!\S)');
				element.className = element.className.replace(regex , '');
			}
			function toggleClassName(element, className) {
				if (containsClassName(element, className)) {
					removeClassName(element, className);
				} else {
					addClassName(element, className);
				}
			}
			
			function navigate(id) {
				closeSearchAndMenu();
				var pages = document.querySelectorAll(".page");
				for (var i = 0; i < pages.length; i++) {
					pages[i].style.display = "none";
				}
				if (!document.getElementById(id + "-page")) console.log('wtf id="' + id + '"');
				document.getElementById(id + "-page").style.display = "block";
				
				if (isMapPage()) {
					makeMapLocationListAvalible();
				} else {
					makeMapLocationListUnavilible();
				}
				if (id == 'map-canvas') {
					google.maps.event.trigger(HR.map, 'resize');
					document.getElementById("nav-search").style.display = "block";
				} else {
					document.getElementById("nav-search").style.display = "none";
				}
			}
			
			HR.updateLocationList = function() {
				if (!containsClassName(document.getElementById("map-locations-list"), 'open')) return;
				
				var listContainer = document.getElementById("map-locations-list-content");
				var list = document.createElement('ul');
				var closest = [];
				for (var placeId in HR.visibleMarkersMap) {
					var marker = HR.visibleMarkersMap[placeId];
					if (HR.currentPosition) {
						marker.__ppDistanceToCurrentPosition = parseInt(distance(HR.currentPosition.latitude, HR.currentPosition.longitude, marker.getPosition().lat(), marker.getPosition().lng())); 
					}
					closest.push(marker);
				}
				if (HR.currentPosition) closest.sort(function(a, b) { return a.__ppDistanceToCurrentPosition - b.__ppDistanceToCurrentPosition; });

				if (closest.length <= 0) {
					var li = document.createElement('li');
					li.innerHTML = 'Inga platser.';
					list.appendChild(li);
				} else {
					for (var i = 0; i < 20 && i < closest.length; i++) {
						if (!HR.currentPosition) continue;

						var marker = closest[i];						
						var content = "<span>" + marker.__ppDistanceToCurrentPosition + "&nbsp;m</span>";
						content += marker.__ppAttributesMap['Innehavare'];
						content += (marker.__ppAttributesMap['Adress'] ? '<br>' + marker.__ppAttributesMap['Adress'] : "");

						var li = document.createElement('li');
						li.innerHTML = content;
						li.onclick = function() {
							console.log('clicked');
							marker.getMap().panTo(marker.getPosition());
						}
						list.appendChild(li);
					}
				}
				listContainer.innerHTML = '';
				listContainer.appendChild(list);
			}
			
			HR.toggleMapLocationList = function() {
				var mapLocationList = document.getElementById("map-locations-list");
				if (mapLocationList) {
					if (containsClassName(mapLocationList, 'open')) {
						removeClassName(mapLocationList, 'open');
						document.getElementById("map-locations-list-icon").className = 'icon-chevron-left';
						mapLocationList.style.width = '';
					} else {
						addClassName(mapLocationList, 'open');
						document.getElementById("map-locations-list-icon").className = 'icon-chevron-right';
						HR.updateLocationList();
						if (document.documentElement.clientWidth < 500) {
							mapLocationList.style.width = document.documentElement.clientWidth + "px";
						}
					}
				}
			}
			function makeMapLocationListUnavilible() {
				var mapLocationList = document.getElementById("map-locations-list");
				removeClassName(mapLocationList, 'open');
				document.getElementById("map-locations-list-icon").className = 'icon-chevron-left';
				mapLocationList.style.width = '';
				mapLocationList.style.display = "none";
			}
			function makeMapLocationListAvalible() {
				if (isMapPage()){
					document.getElementById("map-locations-list").style.display = "block";
				}
			}
			function isMapPage() {
				var id = location.hash.substring(1);
				return (id.length == 0 || id == "map-canvas");
			}
			function isOpenNow(tidsPeriod, dagar, tider) {
				var now = new Date();
				var isOpen = true;

				if (tidsPeriod != 'Året runt') {
					if (!tidsPeriod.indexOf('Mellan ') == 0) { console.log('Unhandled tidsPeriod: ' + tidsPeriod); return false; }
					var tidsPeriodStart = fromSlashedToDate(tidsPeriod.split(' ')[1].split('-')[0], now);
					var tidsPeriodEnd = fromSlashedToDate(tidsPeriod.split(' ')[1].split('-')[1], now);
					if (now.getTime() < tidsPeriodStart || now.getTime() > tidsPeriodEnd) return false;
				}

				if (dagar != 'Alla dagar') {
					var parts = dagar.split(' till ');
					if (parts.length != 2) { console.log('strange dagar=' + dagar); return false; };
					var startDayNumber = dayToNumber(parts[0]);
					var endDayNumber = dayToNumber(parts[0]);
					var includedDays = {};
					if (endDayNumber >= startDayNumber) {
						for (var day = startDayNumber; day <= endDayNumber; day++) includedDays[day] = true;
					} else {
						console.log('strange dagar=' + dagar);
						return false;
					}
					if (!includedDays[now.getDay()]) return false;
				}
				
				if (tider != 'Dygnet Runt') {
					if (tider.indexOf('Från ') == -1 || tider.indexOf(' till ') == -1) { console.log('strange tider=' + tider); return false; }
					tider = tider.substring('Från '.length);
					var parts = tider.split(' till ');
					var startMinutes = timeStringToMinutes(parts[0]);
					var endMinutes = timeStringToMinutes(parts[1]);
					if (startMinutes > endMinutes) { endMinutes += 24 * 60; }
					var nowMinutes = now.getHours() * 60 + now.getMinutes();
					if (nowMinutes < startMinutes || nowMinutes > endMinutes) return false;
					
				}
				return true;
			}
			function fromSlashedToDate(tidsPeriod, now) {
				var parts = tidsPeriod.split('/');
				return new Date(now.getYear(), parts[1], parts[0]);
			}
			function dayToNumber(dayString) {
				switch (dayString.toLowerCase()) {
					case 'måndag': return 1;
					case 'tisdag': return 2;
					case 'onsdag': return 3;
					case 'torsdag': return 4;
					case 'fredag': return 5;
					case 'lördag': return 6;
					case 'söndag': return 0;
					default: alert('Unhandled day: ' + dayString);
				}
			}
			function timeStringToMinutes(timeString) {
				var parts = timeString.split(':');
				return parseInt(parts[0]) * 60 + parseInt(parts[1]);
			}

			// Tells if we're in "Hjärtsäker zon"
			function handlePositionStatus(newStatus, closest) {
				newStatus = newStatus;
				var statusHtml = "";
				if (newStatus === "unknown") {
					statusHtml = "<i class='icon-question icon-large' style='color:black'></i>"
						+ "<em>Det går inte att avgöra om du är i en Hjärtsäker zon eftersom din position inte kan hämtas.</em>"
				} else if (newStatus == "true") {
					statusHtml = "<i class='icon-check-sign icon-large' style='color:green'></i>"
						+ " Du befinner dig i en Hjärtsäker zon!";
				} else {
					statusHtml = "<i class='icon-minus-sign-alt icon-large' style='color:red'></i>"
						+ " Du befinner dig <strong>inte</strong> i en Hjärtsäker zon.";
				}
				document.getElementById("position-status").innerHTML = statusHtml;
				document.getElementById("facebook").style.display = newStatus == "true" ? "block" : "none";
				document.getElementById("heart").className = newStatus == "true" ? "icon-heart" : "icon-heart-empty";
				
				var listHtml = "";
				if (newStatus == "true") {
					listHtml += "Dina närmaste hjärtstartare är:"
						+ "<ul>";
					for (var i = 0; i < closest.length; i++) {
						var point = closest[i];
						listHtml += "<li><span>" + parseInt(point.distance) + " &nbsp;m</span> "
							+ point.owner
							+ (point.address ? "<br>" + point.address : "");
					}
					listHtml += "</ul>";
				}
				document.getElementById("position-list").innerHTML = listHtml;
			}

			window.addEventListener("load", function() {
				handlePositionStatus("unknown");

				setTimeout(function() { window.scrollTo(0, 1); }, 10);
				
				// Silly IOS fix
				if (navigator.userAgent.toLowerCase().match(/(ipad|iphone|ipod)/g)) {
					var pages = document.querySelectorAll(".page");
					for (var i = 0; i < pages.length; i++) {
						var page = pages[i];
						var documentHeight = document.documentElement.clientHeight;
						if (page.clientHeight + 60 > documentHeight) {
							pages[i].style.height = (documentHeight + 60) + "px";
						}
					}
				}

				var links = document.querySelectorAll(".menu-link");
				for (var i = 0; i < links.length; i++) {
					var link = links[i];
					link.onclick = function() {
						// If we select the same page we're on, no "hash change" event occurs
						if (link.href.indexOf(location.hash) != -1) {
							navigate(location.hash.substring(1));
						}
					}
				}
				
				document.getElementById("body").onclick = function() {
					closeSearchAndMenu();
					makeMapLocationListAvalible();
				};
				document.getElementById("nav").onclick = function(event) {
					event.stopPropagation();
				};
				if (location.hash) {
					var id = location.hash.substring(1);
					if (id.length == 0) id = "map-canvas";
					navigate(id);
				}
				HR.currentPosition = null; // has latitude and longitude floats
				navigator.geolocation.watchPosition(function(position) {
					var ZONE = 250;
					HR.currentPosition = position.coords;
					var southWestLat = position.coords.latitude + (180/Math.PI)*(-ZONE/6378137);
					var southWestLon = position.coords.longitude + (180/Math.PI)*(-ZONE/6378137)/Math.cos(Math.PI/180 * position.coords.latitude);
					var northEastLat = position.coords.latitude + (180/Math.PI)*(ZONE/6378137);
					var northEastLon = position.coords.longitude + (180/Math.PI)*(ZONE/6378137)/Math.cos(Math.PI/180 * position.coords.latitude);
					var bboxParam = southWestLon + "," + southWestLat + "," + northEastLon + "," + northEastLat;
					var requestUrl = HR.buildKmlRequestUrl(bboxParam);
					var xhr = new XMLHttpRequest();
					xhr.onreadystatechange = function() {
						if (xhr.readyState != 4) return;
						var points = xhr.responseXML.getElementsByTagName("Placemark");
						var status = "false";
						var closest = [];
						for (var i = 0; i < points.length; i++) {
							var point = points[i];
							var lat = parseFloat(point.getElementsByTagName("latitude")[0].textContent);
							var lon = parseFloat(point.getElementsByTagName("longitude")[0].textContent);
							var dist = distance(position.coords.latitude, position.coords.longitude, lat, lon);
							if (dist <= ZONE) {
								status = "true";
								var map = getAttributesMap(point);
								closest.push({
									owner: map["Innehavare"],
									address: map["Adress"],
									distance: dist
								});
							}
						}
						closest.sort(function(a, b) {
							return a.distance - b.distance;
						});
						handlePositionStatus(status, closest);
					}
					xhr.open("GET", requestUrl, true);
					xhr.send();

				}, function(error) {
					handlePositionStatus("unknown");
				}, { enableHighAccuracy: true });
			});

			// From http://studiowhiz.com/2010/10/02/google-maps-v3-distancefrom/
			function distance(lat1, lng1, lat2, lng2) {
				   var radianLat1 = lat1 * ( Math.PI  / 180 );
				   var radianLng1 = lng1 * ( Math.PI  / 180 );
				   var radianLat2 = lat2 * ( Math.PI  / 180 );
				   var radianLng2 = lng2 * ( Math.PI  / 180 );
				   // sort out the radius, MILES or KM?
				   var earth_radius = 6378100; // (km = 6378.1) OR (miles = 3959) - radius of the earth
				 
				   // sort our the differences
				   var diffLat =  ( radianLat1 - radianLat2 );
				   var diffLng =  ( radianLng1 - radianLng2 );
				   // put on a wave (hey the earth is round after all)
				   var sinLat = Math.sin( diffLat / 2  );
				   var sinLng = Math.sin( diffLng / 2  ); 
				 
				   // maths - borrowed from http://www.opensourceconnections.com/wp-content/uploads/2009/02/clientsidehaversinecalculation.html
				   var a = Math.pow(sinLat, 2.0) + Math.cos(radianLat1) * Math.cos(radianLat2) * Math.pow(sinLng, 2.0);
				 
				   // work out the distance
				   var distance = earth_radius * 2 * Math.asin(Math.min(1, Math.sqrt(a)));

				   // return the distance
				   return distance;
			}

			window.onhashchange = function() {
				var id = location.hash.substring(1);
				if (id.length == 0)	id="map-canvas";
				navigate(id);
				window.scrollTo(0, 1);
			}
    })()</script>
	</head>

	<body id="body">
		<div id="header">
	 		<div id="logo">
	 			<a id="logo-a" href="#about"
	 				onclick="window.scrollTo(0, 1); if (this.href.indexOf(location.hash)!=-1) { if (this.href.indexOf('#about')!=-1) { this.href='#map-canvas'; } else { this.href='#about'; } }"></a>
	 		</div>
			<ul id="nav">
				<li id="nav-search">
					<a href="#" onclick="HR.showSearchOrMenu('nav-search'); document.getElementById('search').focus(); return false;">
						<i class="icon-search" title="Sök"></i>
					</a>
					<ul>
						<li>
							<input type="search" id="search" placeholder="Sök på adress">
						</li>
					</ul>
				</li>
				<li id="nav-hjartsaker-zon">
					<a class="menu-link" href="#hjartsaker-zon"><i class="icon-heart-empty" id="heart"></i></a>
				</li>
				<li id="nav-menu">
					<a href="#" onclick="HR.showSearchOrMenu('nav-menu'); return false;">
						<i class="icon-reorder" title="Menu"></i>
					</a>
					<ul>
						<li><a class="menu-link" href="#map-canvas">Karta</a></li>
						<li><a class="menu-link" href="#hjartsaker-zon">Hjärtsäker zon</a></li>
						<li><a class="menu-link" href="#contact">Kontakt</a></li>
						<li><a class="menu-link" href="#about">Om Sveriges Hjärtstartarregister</a></li>
					</ul>
				</li>
			</ul>
		</div>
	
		<div id="map-locations-list">
			<div onclick="HR.toggleMapLocationList(); return false;">
				<i id="map-locations-list-icon" class="icon-chevron-left"></i>
			</div>
			<div id="map-locations-list-content"></div>
		</div>
		
		<div class="page" id="map-canvas-page"></div>
		
		<div class="page text-content" id="contact-page" style="display:none">
			<h1>Kontakta Sveriges Hjärtstartarregister</h1>
			<p>
				<strong>David Fredman</strong>
				<br>
				E-post: <a href="mailto:david@hjartstartarregistret.se">david@hjartstartarregistret.se</a>
			</p>
			<p>
				<strong>Joel Sundberg</strong>
				<br>
				Telefon: 08-629 63 79
				<br>
				E-post: <a href="mailto:joel@hjartstartarregistret.se">joel@hjartstartarregistret.se</a>
			</p>
			<p>
				För problem med validering, registrering eller ändring av hjärtstartare, vänligen maila Joel.
			</p>
		</div>
		
		<div class="page text-content" id="hjartsaker-zon-page" style="display:none">
			<div style="text-align:center"><img src="styles/HjartsakerZon-100.png"></div>
			<p id="position-status"></p>
			<div id="fb-root"></div>
			<script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/sv_SE/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script>
			<div id="facebook" style="display:none">
				<p>Du kan <em>Skicka</em> en Facebook-status för att berätta att du är i en Hjärtsäker zon.</p>
				<div class="fb-like" data-href="http://m.hjartstartarregistret.se/#hjartsaker-zon" data-send="true" data-layout="button_count" data-width="300" data-show-faces="true" data-action="recommend"></div>
			</div>
			<hr>
			<p><strong>Hjärt-Lungfondens</strong> sida <a href="http://www.hjart-lungfonden.se/Stod-oss/Vara-kampanjer/180sekunder/Hjartsaker-zon1/">om Hjärtsäker zon</a>.</p>
			<hr>
			<p id="position-list"></p>
		</div>
		
		<div class="page text-content" id="about-page" style="display:none">
			<h1>Om Sveriges Hjärtstartarregister</h1>
			<p>Civilförsvarsförbundet och Svenska HLR-rådet har tagit initiativet till Sveriges hjärtstartarregister och Hjärt-Lungfonden är en samarbetspartner. Registret vilar helt på ideell grund. Detta är ett nationellt register för alla de hjärtstartare som finns tillgängliga för allmänheten i Sverige. Detta är det första och hittills enda i sitt slag i Sverige, liknande finns runt om i Europa.<br /><br /> Ett flertal projekt pågår runt om i landet som syftar till att öka överlevnaden vid plötsligt hjärtstopp genom att göra hjärtstartare tillgängliga i samhället. Många företag, föreningar och privatpersoner har också köpt in hjärtstartare på eget initiativ.</p>
			<p>Genom Sveriges hjärtstartarregister samlas nu informationen om hjärtstartarnas tillgänglighet på ett ställe och deras geografiska placering görs tillgänglig för allmänheten.</p>
			<p>Via <a href="http://www.hjartstartarregistret.se/">www.hjartstartarregistret.se</a> kan allmänheten nu få bättre information om var hjärtstartare finns placerade. Denna kunskap kan visa sig livsavgörande om ett plötsligt hjärtstopp inträffat. Ju snabbare en hjärtstartare kommer till den nödställde desto större är chanserna att den räddas till livet. </p>
			<p>Registret planeras inom den närmaste framtiden ge möjlighet för larmcentralerna att i samband med larm som tolkas som ett hjärtstopp, upplysa inringaren om var närmaste hjärtstartare finns för snabb livräddande insats i väntan på ambulans.</p>
			<p><strong>I det webbaserade registret har du/ni som innehavare av en eller flera hjärtstartare möjlighet att uppge var er hjärtstartare är placerad. Registreringen är gratis, helt frivillig och innebär inga krav, däremot kan registreringen bidra till att rädda liv</strong>.</p>
			<p>Registrera din hjärtstartare redan idag!</p>
			
			<h2>Om Mobilsajten</h2>
			<p>Team PING PONG skapade mobilsajten under A Helping Hack i maj 2013 (<a href="http://www.helpinghack.se">www.helpinghack.se</a>).
			<p>Teamet bestod av Magnus Widerberg, Fredrik Fornwall, Simon Samnegård och Thomas Cairns.</p>
		</div>
		
	</body>
</html>
